package cn.dblearn.blog.manage.file;

import cn.dblearn.blog.common.Result;
import cn.dblearn.blog.common.exception.MyException;
import cn.dblearn.blog.common.exception.MyFileException;
import cn.dblearn.blog.entity.oss.OssResource;
import cn.dblearn.blog.manage.oss.service.OssResourceService;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @program: blog
 * @ClassName SpringMvcUploadController
 * @description:
 * @author: haochen
 * @create: 2020-07-04 22:53
 * @Version 1.0
 **/
@RestController
@CrossOrigin
@Slf4j
public class SpringMvcUploadController {

	@Value("${file.path}")
	String savePath;
	@Value("${file.url}")
	String preurl;

    @Autowired
    private OssResourceService ossResourceService;
	
	@PostMapping("/admin/fileupload")
	public Result fileupload(MultipartFile file, @RequestParam(name = "use", required = false) String use) {
		// 上传文件项
		// use 用途 可以用来文件分类
		String filename = file.getOriginalFilename();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String saveName = uuid + "." + filename.substring(filename.lastIndexOf(".") + 1);
//    String path = "D:\\TEMP\\upload";
//    String path = "D:\\TEMP\\upload";
		try {
			file.transferTo(new File(savePath, saveName));
		} catch (IOException e) {
			// 简单记录日志
			log.info("上传该图片失败,文件名:{}", filename);
			throw new MyFileException();
		}
//		String visitPath = "http://127.0.0.1:8080/dbblog/f/" + saveName;
		String visitPath = preurl + saveName;
		
        OssResource resource=new OssResource(visitPath,file.getOriginalFilename());
        ossResourceService.save(resource);
        
        return Result.ok().put("resource", resource);
		
//		JSONObject jsonObject = new JSONObject();
//		jsonObject.fluentPut("url", visitPath);
//		jsonObject.fluentPut("code", 200);
//		return jsonObject;
	}

}
